package org.apache.lucene.index;

import java.io.IOException;

import org.apache.lucene.store.ByteArrayIndexInput;
import org.apache.lucene.store.ByteArrayIndexOutput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;

/**
 * Fields for single document.  Contains term numbers to lookup actual terms
 * from dictionary.
 */
public class TagFieldData {
  public long version;
  public Field[] fields;
  
  public TagFieldData(byte[] bytes) throws IOException {
    ByteArrayIndexInput input = new ByteArrayIndexInput(bytes);
    version = input.readVLong();
    int numFields = input.readInt();
    fields = new Field[numFields];
    for (int x=0; x < fields.length; x++) {
      int fieldNum = input.readVInt();
      int termNum = input.readVInt();
      byte tlog = input.readByte();
      boolean tlogb = false;
      if (tlog == 1) tlogb = true;
      fields[x] = new Field(fieldNum, termNum, tlogb); 
    }
  }
  
  public static class Field {
    public final int fieldNum;
    public final int termNum;
    public final boolean tlog;
    
    public Field(int fieldNum, int termNum, boolean tlog) {
      this.fieldNum = fieldNum;
      this.termNum = termNum;
      this.tlog = tlog;
    }
    
    public void writeTo(IndexOutput output) throws IOException {
      output.writeVInt(fieldNum);
      output.writeVInt(termNum);
      byte b = 0;
      if (tlog) b = 1;
      output.writeByte(b);
    }
  }
  
  public byte[] getBytes() throws IOException {
    RAMOutputStream output = new RAMOutputStream();
    output.writeVLong(version);
    output.writeVInt(fields.length);
    for (int x=0; x < fields.length; x++) {
      fields[x].writeTo(output);
    }
    int length = (int)output.length();
    ByteArrayIndexOutput byteArrayIndexOutput = new ByteArrayIndexOutput(length);
    return byteArrayIndexOutput.toByteArray();
  }
}
